package cn.kgc.springmvc.day02.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 课工场
 * @date 2024/5/6
 * @description    springmvc中转发和重定向的使用
 *
 * forward:  声明页面跳转方式为转发
 * redirect: 声明页面跳转方式为重定向
 */
@Controller
@RequestMapping("fr")
public class FRController {

    // 转发   -> 视图解析
    @RequestMapping("m1")
    public ModelAndView method1() {

        System.out.println("hello  springmvc");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");
        modelAndView.addObject("info","参数的接收");

        return modelAndView;
    }


    //  String  默认是视图名    ->  视图解析器  -> 转发视图
    @RequestMapping("m2")
    public String method2() {
        return "hello";
    }


    //  "forward:hello"    不会经过视图解析器      转发
    @RequestMapping("m3")
    public String method3() {
        return "forward:/hello.jsp";
    }

    // 转发   不会经过视图解析器
    @RequestMapping("m4")
    public void method4(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/hello.jsp").forward(request,response);
    }

    // 重定向
    @RequestMapping("m5")
    public void method5(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        session.setAttribute("info","hello redirect");
        response.sendRedirect(request.getContextPath()+"/hello.jsp");
    }


    //  "redirect:/hello.jsp"    不会经过视图解析器      重定向
    @RequestMapping("m6")
    public String method6() {
        return "redirect:/hello.jsp";
    }
}
